import React, {Component} from 'react';
import {withRouter,Link, Switch, Route} from 'react-router-dom'
import { Layout, Menu,  Icon ,Button,DatePicker,Input,Radio,Checkbox,TimePicker,Select,message} from 'antd';
import 'moment/locale/zh-cn';
import moment from 'moment';
import u from '../../common.js'
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import locale from 'antd/lib/date-picker/locale/zh_CN';
import $ from "jquery"
import Loading from "./../loading"//加载中样式


import "../../static/systemSetup/system-warning.styl"

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
const format = 'hh:mm:ss';

const options = [
  { label: '正面', value: '0正面',},
  { label: '中立', value: '1中立', },
  { label: '负面', value: '2负面',},
];
const mediaOptions = [
  { label: '新闻', value: '0新闻' },
  { label: '论坛', value: '1论坛' },
  { label: '平面媒体', value: '2平面媒体' },
  { label: '博客', value: '3博客' },
  { label: '贴吧', value: '4贴吧' },
  { label: '外文网站', value: '5外文网站' },
];

export default class SystemWarning extends React.Component{
    state = {
         open: false,
         value: 0,//周末预警
         value1:[],//舆情属性
         value1Type:['0正面','1中立','2负面'],
         value1Show: [],//舆情显示
         value2Show: [],//媒体显示
         value2:[],//媒体属性
         value2Type:['0新闻','1论坛','2平面媒体','3博客','4贴吧','5外文网站'],
         show:false,
         list:[],//网络预警关键词
         start:'',//开始时间
         mailChecked:true,//邮件预警
         webChecked:true,//web预警
         hasData:false,//是否有预警信息
         newAdmin:true,
         list2:[],//微信预警关键词
     };
     
// 日期
  handleOpenChange = (open) => {
    this.setState({ open });
  }

// 单选按钮
onChange = (e) => {
    this.setState({
      value: e.target.value,
    });
  }
  //舆情属性
  sentiment =(checkedValues)=>{

    let value1=[]
    checkedValues.forEach(item=>{
      value1.push(item.slice(0,1))
    })

     this.setState({
       value1:value1,
     })//bug1 不同步
  }
    //媒体类型

    media =(checkedValues)=>{
      let value2=[]
      checkedValues.forEach(item=>{
        value2.push(item.slice(0,1))
      })

     this.setState({
       value2:value2,
     })//bug1 不同步
  }
 //显示和隐藏
show = () =>{
  //点击按钮显示预警设置
 $('.warnBottom').css({display:"block"});

}
//网络添加关键词
addKeywords = () =>{
    var arr = this.state.list.slice(0);
    var addKeyVal=$.trim($('.addKey').val());
    if(addKeyVal.length<1){
      message.error('关键词长度不能为0');
      return
    }else{
      arr.push($('.addKey').val());
      this.setState({
        list:arr
      },()=>{
        console.log(this.state.list)
      })
      $('.addKey').val('')
    }
   
}
//微信添加关键词
addKeywords2 = () =>{
  console.log(this.state.list2)
  // var arr = this.state.list2.slice(0)||[];
  var arr=this.state.list2
  var addKeyVal=$.trim($('.addKey2').val());
  if(addKeyVal.length<1){
    message.error('关键词长度不能为0');
    return
  }else{
    arr.push($.trim($('.addKey2').val()));
    this.setState({
      list2:arr
    },()=>{
      console.log(this.state.list2)
    })

    $('.addKey2').val('')
  }
 
}
//网络删除关键词
delKeywords =(index) =>{
  var arr = this.state.list.slice(0);
  arr.splice(index,1);
  this.setState({
    list:arr
  })
  
}
//微信删除关键词
delKeywords2 =(index) =>{
  var arr = this.state.list2.slice(0);
  arr.splice(index,1);
  this.setState({
    list2:arr
  })
  
}
//新增预警接口
addSimple=()=>{
  // console.log($('.mailFile input').val())
  let mailVal=$('.mailFile input').val()
  if(this.state.value1.length<1 && this.state.value2.length<1){
    message.error('预警条件不能为空');
  }else{
    console.log($.trim(this.state.list2.toString()))
    u.addSimple({
      key_group:this.state.list.toString(),//网络关键词
      keyWord:this.state.list2[0]=='' ? $.trim(this.state.list2.toString().substr(1)) : $.trim(this.state.list2.toString()),//微信关键词
    quality:this.state.value1.toString(),//舆情属性
    type:this.state.value2.toString(),//媒体属性
    mail_switch:$('.mail span input').is(':checked')==false ? 0:1,//邮件预警
    email:mailVal,//邮件地址
    web_switch:$('.webSwitch span input').is(':checked')==false ? 0:1,//web预警
    start_time:$('.startTime div input').val()+' '+$('.startDetail input').val(),//开始时间
    end_time:$('.endTime div input').val()+' '+$('.endDetail input').val(),//结束时间
    workday_switch:this.state.value,//周末预警
    rate:$('.rate .ant-select-selection-selected-value').text().replace(/[^0-9]/ig,""),//预警频次
  
    },data=>{
      console.log(data);
      message.success('预警设置成功');
      //有bug
      // console.log($('.webSwitch span input').is(':checked')==false && $('.mail span input').is(':checked')==false )
      // if($('.webSwitch span input').is(':checked')==false && $('.mail span input').is(':checked')==true ){
      //   message.error('请选择预警通知类型');
      // }else{
      //   message.success('预警设置成功');
      // }
     
    })
  }

  
}

componentDidMount(){
  //显示隐藏
 
    //查询预警信息接口
     u.simple(data=>{
       if(!data.data.result){
         //没有预警显示按钮
        $('.warnSwitch').css({display:"block"})
          this.setState((prevState,props)=>({
            newAdmin:false
          }))
         return
        }else{
         console.log(data.data.result)
          this.setState({
            hasData:true,//有预警信息
            value1:[data.data.result.quality],//舆情属性  数字
          })

          //直接反显 复选框反显问题
          $('.warnBottom').css({display:"block"});
         
          $('.rate .ant-select-selection-selected-value').text(data.data.result.rate+'分钟');//频次
          $('.mailFile input').val(data.data.result.email)//邮件地址
          data.data.result.mail_switch==1?$('.mail span input').prop('checked','true'):$('.mail span input').prop('checked','false')//邮件预警
          
          // $('.startTime div input').val(data.data.result.start_time.substring(0,data.data.result.start_time))
          // $('.startTime div input').val(data.data.result.start_time.split(' ')[0])//bug2 时间控件显示问题
      
          console.log(data.data.result.keyWord)
          this.setState({
            list:data.data.result.key_group.split(','),
            value1:data.data.result.quality.split(','),
            value2:data.data.result.type.split(','),
            start:data.data.result.start_time.split(' ')[0],
            mailChecked:data.data.result.mail_switch == 1 ? true : false,
            webChecked:data.data.result.web_switch == 1 ? true : false,
            value:data.data.result.workday_switch ==0 ? 0 : 1,
            list2:data.data.result.keyWord.split(','),
          },() =>{
            let value1Show=[]
            let value2Show=[]
            console.log(data.data.result.keyWord.split(','))
            this.state.value1.forEach(item=>{
              value1Show.push(this.state.value1Type[item])
            })
            this.state.value2.forEach(item=>{
              value2Show.push(this.state.value2Type[item])
            })
            this.setState((prevState) => ({
              value1Show: value1Show,
              value2Show: value2Show
            }),() =>{

            })

            })
            //舆情反显
        }
   
     })
    
   
}
//点击邮件地址的x清空input内容
empty=()=>{
  $('.mailFile input').val('')
}
  handleClose = () => this.setState({ open: false })
    render(){
      const suffix = <Icon type="close"  onClick={this.empty}/>
        return(
            <div className="warnContainer">
              <Loading className="loadingPage"/>
               <div className="warnTop">
                 <Button type="primary" onClick={()=>this.show()} className='warnSwitch' style={{display:"none"}}>开启预警</Button>
                 <p>关键词预警：与您设置的关键词相关的舆情，将呈现在预警信息模块，同时您可以选择邮件、页面弹窗接受预警通知。</p>
               </div>
               <div className="warnBottom">
               {/* 网络预警条件 */}
                  <div className="warnBox">
                      <h4>网络预警条件</h4>
                      <div className="warnItem" style={{alignItems:"inherit"}}>
                         <div className="label">
                           <span>关键词:</span>
                         </div>
                         <div className="add">
                            <div className="addTop">
                              <Input className="addKey" style={{marginRight:"20px",width:"185px"}}/>
                              <Button type="primary" onClick={()=>this.addKeywords()}>添加</Button>
                            </div>
                            <div  className="addBottom">
                              {
                                this.state.list.map((item,index)=>{
                                  return(   <button key={index}>{item}
                                    <Icon type="close"  className="closeBtn"  style={{marginLeft:"10px"}} onClick={()=>this.delKeywords(index)}/>
                                    </button>)
                                })
                              }
                            </div>
                         </div>
                      </div>
                      <div className="warnItem">
                        <div className="label">
                           <span>舆情属性：</span>
                         </div>
                         <div className="options">
                            {
                              this.state.newAdmin?(this.state.value1Show.length > 0 && <CheckboxGroup options={options} onChange={this.sentiment} defaultValue={this.state.value1Show}/>):(<CheckboxGroup options={options} onChange={this.sentiment} defaultValue={this.state.value1Show}/>) 
                            }
                         </div>
                      </div>
                      <div className="warnItem">
                        <div className="label">
                           <span>媒体类型：</span>
                         </div>
                         <div className="options">
                          {
                             this.state.newAdmin?(this.state.value2Show.length >0 && <CheckboxGroup options={mediaOptions}  onChange={this.media} defaultValue={this.state.value2Show}/>):(<CheckboxGroup options={mediaOptions}  onChange={this.media} defaultValue={this.state.value2Show}/>)
                          }
                           
                         </div>
                      </div>
                  </div>
                     {/* 微信预警条件 */}
                  <div className="warnBox">
                      <h4>微信预警条件</h4>
                      <div className="warnItem" style={{alignItems:"inherit"}}>
                         <div className="label">
                           <span>关键词:</span>
                         </div>
                         <div className="add">
                            <div className="addTop">
                              <Input className="addKey2" style={{marginRight:"20px",width:"185px"}}/>
                              <Button type="primary" onClick={()=>this.addKeywords2()}>添加</Button>
                            </div>
                            <div  className="addBottom">
                              {
                                this.state.list2.length >= 0 ? 
                                this.state.list2.map((item,index)=>{
                                  
                                  return(    item.trim()===''?'':<button key={index}>{item.trim()}
                                    <Icon type="close"  className="closeBtn"  style={{marginLeft:"10px"}} onClick={()=>this.delKeywords2(index)}/>
                                    </button>)
                                }) :''
                              }
                            </div>
                         </div>
                      </div>
                  </div>
                  {/* 预警通知 */}
                  <div className="warnBox">
                     <h4>预警通知</h4>
                     <div className="warnItem" style={{alignItems:"baseline"}}>
                        <div className="label">
                           <span>邮件预警：</span>
                        </div>
                        <div className="add">
                           <div  className="addTop">
                             <Checkbox style={{marginRight:"1%",marginTop:"1%"}} className="mail" checked={this.state.mailChecked}>开启预警</Checkbox>
                             {/* <a href="javascript:;">新增地址</a> */}
                           </div>
                            <div className="addSite">
                              <Input placeholder="请输入邮件地址" 
                                style={{width:"208px",marginTop:"1%"}}
                                suffix={suffix}
                                className="mailFile"
                               />
                            </div> 
                        </div>
                     </div>
                     <div className="warnItem">
                        <div className="label">
                           <span>Web预警：</span>
                         </div>
                         <div className="options">
                           <Checkbox className="webSwitch" checked={this.state.webChecked}>开启预警</Checkbox>
                         </div>
                      </div>
                  </div>
                  {/* 时间设置 */}
                  <div className="warnBox">
                    {/* <h4>短信\邮件预警时间设置 <i style={{fontSize:"12px",fontStyle:"normal"}}>(APP预警请进入APP设置)</i></h4> */}
                    <h4>短信\邮件预警时间设置</h4>
                    <div className="warnItem">
                        <div className="label">
                           <span>预警时间：</span>
                        </div>
                        <div className="calendar">
                          <DatePicker  style={{marginRight:"1%"}} 
                          locale={locale}
                          defaultValue={moment('2018-08-31', 'YYYY-MM-DD')}
                          className="startTime"
                          />
                          <TimePicker defaultValue={moment('9:00', format)} 
                          style={{marginRight:"1%"}}
                          use12Hours
                          format={format} 
                          className="startDetail"
                          />
                          <i style={{marginRight:"1%",fontStyle:"normal",fontSize:"12px"}}>To</i>
                          <DatePicker  style={{marginRight:"1%"}} 
                          defaultValue={moment('2018-08-31', 'YYYY-MM-DD')}
                          locale={locale}
                          className="endTime"
                          />
                          <TimePicker defaultValue={moment('5:00', format)} 
                          style={{marginRight:"1%"}}
                          format={format} 
                          use12Hours
                          className="endDetail"
                          />
                        </div>
                    </div>
                    <div className="warnItem">
                        <div className="label">
                           <span>周末预警：</span>
                        </div>
                        <div className="options">
                          <RadioGroup onChange={this.onChange} value={this.state.value}>
                              <Radio value={0}>预警</Radio>
                              <Radio value={1}>不预警</Radio>
                          </RadioGroup>
                        </div>
                    </div>
                    <div className="warnItem" style={{alignItems:"baseline"}}>
                        <div className="label">
                           <span>预警频次：</span>
                        </div>  
                        <div className="add">
                          <div  className="addTop" style={{marginBottom:"1%"}}>
                                <Select defaultValue="5分钟" style={{marginRight:"2%"}} className="rate">
                                        <Option value="Option1">5分钟</Option>
                                        <Option value="Option2">10分钟</Option>
                                </Select>
                                <p>预警一次（预警频次设置可缓解实时预警的高频干扰）</p>
                          </div>
                          <p style={{marginBottom:"55px",color:"#9ba2ab",fontSize:"12px"}}>短信每次最多显示1条舆情信息,邮件每次最多显示30条舆情信息</p>
                          <div className="submit">
                            <Button type="primary" style={{width:"100px",marginRight:"20px"}} onClick={this.addSimple}>保存</Button>
                            <Button style={{width:"100px"}}>取消</Button>
                          </div>
                        </div>
                    </div>
                  </div>
               </div>
            </div>
        );
    }
}